package game.map
{
	import flash.geom.Point;
	import game.manager.MapManager;
	import game.pathfinder.AStar;
	import game.pathfinder.Node;
	
	/**
	 * ...
	 * @author Kirill Pletnev
	 */
	public class PhysicalMap
	{	
		private var _pathGrid:Vector.<Node>;
		
		private var _numColumns:int;
		private var _numRows:int;
		
		public function PhysicalMap()
		{
			_numColumns = MapManager.instance.columnsMap;
			_numRows = MapManager.instance.rowsMap;
			
			init();
		}
		
		private function init():void
		{
			var numNodes:int = _numColumns * _numRows;
			_pathGrid = new Vector.<Node>(numNodes);
			
			for (var ix:int = 0; ix < numNodes; ix++)
			{
				var location:Point = PhysicalMap.getTilePoint(ix, _numColumns, _numRows);
				_pathGrid[ix] = new Node(location.x, location.y);
			}
		}
		
		public function findPath(startX:int, startY:int, endX:int, endY:int):Vector.<Node>
		{
			var astar:AStar = new AStar();
			var path:Vector.<Node> = null;
			
			if (astar.findPath(this, startX, startY, endX, endY))
			{
				path = astar.path;
			}
			
			return path;
		}
		
		/**
		 * Returns the node at the given coords.
		 */
		public function getNode(column:int, row:int):Node
		{
			var ix:int = PhysicalMap.getTileIndex(column, row, _numColumns, _numRows);
			return _pathGrid[ix];
		}
		
		/**
		 * Sets the node at the given coords as walkable or not.
		 */
		public function setWalkable(column:int, row:int, value:Boolean):void
		{
			var ix:int = PhysicalMap.getTileIndex(column, row, _numColumns, _numRows);
			_pathGrid[ix].walkable = value;
		}
		
		public static function getTilePoint(index:int, numColumns:int, numRows:int):Point
		{
			var column:int = index / numColumns;
			var row:int = index % numColumns;
			return new Point(column, row);
		}
		
		public static function getTileIndex(column:int, row:int, numColumns:int, numRows:int):int
		{
			if (column < 0 || column >= numColumns || row < 0 || row >= numRows)
			{
				return -1;
			}
			return row * numColumns + column;
		}
		
		public function get numColumns():int
		{
			return _numColumns;
		}
		
		public function get numRows():int
		{
			return _numRows;
		}
	}
}